package com.itmake.sample.repeat.interceptor;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.itmake.sample.repeat.annotation.Repeat;
import com.itmake.sample.repeat.constant.RepeatConstant;
import com.itmake.sample.repeat.wrapper.RepeatRequestWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交拦截器
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Component
public class RepeatInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Repeat annotation = method.getAnnotation(Repeat.class);
            if (Objects.nonNull(annotation) && this.isRepeat(request, annotation)) {
                // @TODO 构建重复提交的返回消息，eg：R.no(annotation.message())
                String msg = null;
                ServletUtil.write(response, JSONUtil.toJsonStr(msg), ContentType.JSON.getValue());
                return false;
            }
        }
        return true;
    }

    /**
     * 判断请求 url 和数据是否和上一次相同，
     * 如果和上次相同，则是重复提交表单，有效时间为 10 秒内
     */
    public boolean isRepeat(HttpServletRequest request, Repeat annotation) {
        String nowParams = CharSequenceUtil.EMPTY;
        if (request instanceof RepeatRequestWrapper) {
            RepeatRequestWrapper repeatedlyRequest = (RepeatRequestWrapper) request;
            nowParams = ServletUtil.getBody(repeatedlyRequest);
        }
        // body 参数为空，获取 Parameter 的数据
        if (CharSequenceUtil.isBlank(nowParams)) {
            nowParams = JSONUtil.toJsonStr(request.getParameterMap());
        }

        // 当前参数
        Map<String, Object> nowDataMap = new HashMap<>();
        nowDataMap.put(RepeatConstant.REPEAT_PARAMS, nowParams);
        nowDataMap.put(RepeatConstant.REPEAT_TIME, System.currentTimeMillis());

        // 唯一标识，key + 请求地址
        String url = request.getRequestURI();
        String key = RepeatConstant.REPEAT_REDIS_KEY + url;
        // 获取之前的数据
        Object sessionObj = redisTemplate.opsForValue().get(key);
        if (Objects.nonNull(sessionObj)) {
            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
            if (sessionMap.containsKey(url)) {
                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                // 比较参数和时间
                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) {
                    return true;
                }
            }
        }

        Map<String, Object> cacheMap = new HashMap<>();
        cacheMap.put(url, nowDataMap);
        // 存储当前信息，用于下一次比较
        redisTemplate.opsForValue().set(key, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
        String nowParams = (String) nowMap.get(RepeatConstant.REPEAT_PARAMS);
        String preParams = (String) preMap.get(RepeatConstant.REPEAT_PARAMS);
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval) {
        long time1 = (Long) nowMap.get(RepeatConstant.REPEAT_TIME);
        long time2 = (Long) preMap.get(RepeatConstant.REPEAT_TIME);
        return (time1 - time2) < interval;
    }
}
